<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <!-- 添加按钮 -->
      <el-alert title="注意：只允许为三级分类设置相关参数" type="warning" show-icon></el-alert>
      <div class="cas_container">
        商品分类
        <el-cascader
          v-model="selectKeys"
          :options="cateList"
          :props="CascaderProps"
          @change="handleChange"
          clearable
        ></el-cascader>
      </div>
      <!-- tabs选项卡 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!-- 动态参数面板 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            size="mini"
            type="primary"
            :disabled="isDisable"
            @click="addAttrbuteViseble=true"
          >添加参数</el-button>
          <el-table border stripe :data="manyData" style="width:100%">
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template v-slot="scope">
                <!-- 循环展示的tag标签 -->
                <el-tag v-for="(item,i) in scope.row.attr_vals" 
                :key="i" closable @close="removeTag(i,scope.row)">{{item}}</el-tag>
                <!-- 按钮和输入框的切换区域 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 搜索列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <!-- 操作列 -->
            <el-table-column label="操作" width="180">
              <template v-slot="scope">
                <!-- {{scope.row.attr_id}} -->
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="editQueryParam(scope.row)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="deleteParam(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态参数面板 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            size="mini"
            type="primary"
            :disabled="isDisable"
            @click="addAttrbuteViseble=true"
          >添加属性</el-button>
          <el-table border stripe :data="onlyData" style="width:100%">
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template v-slot="scope">
                <!-- 循环展示的tag标签 -->
                <el-tag v-for="(item,i) in scope.row.attr_vals" 
                :key="i" closable @close="removeTag(i,scope.row)">{{item}}</el-tag>
                <!-- 按钮和输入框的切换区域 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 搜索列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="属性名称"></el-table-column>
            <!-- 操作列 -->
            <el-table-column label="操作" width="180">
              <template v-slot="scope">
                <!-- {{ scope.row }} -->
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="editQueryParam(scope.row)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="deleteParam(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <!-- 添加属性/参数的对话框 -->
      <el-dialog
        :title="'添加'+Text"
        :visible.sync="addAttrbuteViseble"
        width="50%"
        @close="addFormClosed"
      >
        <!-- 表单区域 -->
        <el-form ref="addAttrbuteRef" :model="addForm" label-width="80px" :rules="addFormRules">
          <el-form-item :label="Text" prop="attr_name">
            <el-input v-model="addForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addAttrbuteViseble = false">取 消</el-button>
          <el-button type="primary" @click="addParams">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改属性/参数的对话框 -->
      <el-dialog
        :title="'修改'+Text"
        :visible.sync="editAttrbuteViseble"
        width="50%"
        @close="editFormClosed"
      >
        <!-- 表单区域 -->
        <el-form ref="editAttrbuteRef" :model="editForm" label-width="80px" :rules="addFormRules">
          <el-form-item :label="Text" prop="attr_name">
            <el-input v-model="editForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editAttrbuteViseble = false">取 消</el-button>
          <el-button type="primary" @click="editParams">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 级联选择框中的数据存放的数组
      selectKeys: [],
      cateList: [],
      CascaderProps: {
        // 展示用户看到的字段
        label: "cat_name",
        // 父子关联节点
        children: "children",
        // 触发时机
        expandTrigger: "hover",
        // 提交的数据
        value: "cat_id",
      },
      //   tabs选项卡的激活的面板
      activeName: "many",
      //   动态参数列表数据
      manyData: [],
      // 静态属性参数列表数据
      onlyData: [],
      //   添加属性/参数对话框的布尔值
      addAttrbuteViseble: false,
      //   修改属性/参数的对话框的布尔值
      editAttrbuteViseble: false,
      // 添加的表单
      addForm: {
        attr_name: "",
      },
      //   修改的表单对象
      editForm: {
        attr_name: "",
      },
      // 添加滚动校验规则
      addFormRules: {
        attr_name: [
          { required: true, message: "请输入必填信息", trigger: "blur" },
        ],
      },
      // 输入框和tag切换的配置属性
      // inputVisible: false,
      // inputValue: "",
    };
  },
  methods: {
    // 获取分类数据的方法
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200) {
        return this.$message.error("获取分类列表失败");
      }
      this.cateList = res.data;
    },
    // 级联选择框触发事件
    handleChange() {
      // 只允许为三级分类设置相关参数
      //   console.log(this.selectKeys);
      if (this.selectKeys.length == 0) {
        return (this.manyData = this.onlyData = []);
      }

      this.getParamsList();
    },
    // 方法
    // 获取参数数据

    async getParamsList() {
      if (this.selectKeys.length != 3) {
        return (this.selectKeys = []);
      }
      const { data: res } = await this.$http.get(
        `categories/${this.selectKeys[2]}/attributes`,
        {
          params: { sel: this.activeName },
        }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("获取参数失败");
      }
      // 要在展开行中渲染多个tag标签 需要将data中的attr_vals以空格分割，转换成数组
      res.data.forEach((item) => {
        // console.log(item);
        item.attr_vals = item.attr_vals.length ? item.attr_vals.split(" ") : [];
        // 因为输入框和新增tag切换不能共享data中独一份数据
        // 在遍历的时候手动为每一项 添加自己的布尔值和value值
        item.inputValue = "";
        item.inputVisible = false;
      });
      //   根据激活面板的不同 讲不同的数据挂载在不同的数据根源上
      this.activeName == "many"
        ? (this.manyData = res.data)
        : (this.onlyData = res.data);
      console.log(res);
    },

    // tabs切换会触发的方法
    handleClick() {
      //   console.log(this.activeName);
      this.getParamsList();
    },
    //   重置表单
    addFormClosed() {
      this.$refs.addAttrbuteRef.resetFields();
    },
    // 添加参数/属性
    addParams() {
      this.$refs.addAttrbuteRef.validate(async (boo) => {
        if (!boo) {
          return this.$message.error("请输入必填参数");
        }
        const { data: res } = await this.$http.post(
          `categories/${this.selectKeys[2]}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName,
          }
        );
        if (res.meta.status !== 201) {
          return this.$message.error("添加失败");
        }
        this.$message.success("添加成功");
        // 获取列表参数
        this.getParamsList();
        // 关闭对话框
        this.addAttrbuteViseble = false;
      });
    },
    // 删除属性/参数
    async deleteParam(id) {
      const result = await this.$confirm(
        "此操作将永久删除该属性/参数,是否继续？",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (result !== "confirm") {
        return this.$message.info("已取消删除");
      }
      // 发送请求删除对应的属性
      const { data: res } = await this.$http.delete(
        `categories/${this.selectKeys[2]}/attributes/${id}`
      );
      if (res.meta.status !== 200) {
        return this.$message.error("删除失败");
      }
      this.$message.success("删除成功");
      this.getParamsList();
    },
    // 重置修改的表单数据
    editFormClosed() {
      this.$refs.editAttrbuteRef.resetFields();
      // 对话框关闭将编辑的对象清空
      this.editForm = {};
    },
    // 点击编辑按钮显示表单数据
    editQueryParam(row) {
      //   console.log(row);
      // 正常来说要去发送请求数据 获取到当前行的数据 然后将数据渲染到对话框的表单中
      // 但是直接通过事件传参将当前行的数据传递过来
      this.editForm = row;
      //   this.editForm.attr_name=row.attr_name
      this.editAttrbuteViseble = true;
    },
    // 编辑提交
    editParams() {
      this.$refs.editAttrbuteRef.validate(async (boo) => {
        if (!boo) {
          return this.$message.error("请输入修改信息");
        }
        // 发送请求
        const { data: res } = await this.$http.put(
          `categories/${this.selectKeys[2]}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName,
          }
        );
        if (res.meta.status !== 200) {
          return this.$message.error("添加失败");
        }
        this.$message.success("添加成功");
        // 获取列表参数
        this.getParamsList();
        // 关闭对话框
        this.editAttrbuteViseble = false;
      });
    },
    handleInputConfirm(row) {
      // 非空校验
      if (!row.inputValue.trim().length) {
        row.inputVisible = false;
        row.inputValue = "";
        
        return;
      }
      // 一定要放在代码前面
      row.attr_vals.push(row.inputValue.trim());
      // 调用
      this.saveParams(row);
      // 追加后清空
      row.inputVisible = false;
      // 追加后清空
      row.inputValue = "";
    },
    showInput(row) {
      row.inputVisible = true;
      // 等待dom元素重新更新到页面上 才会触发的函数
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    async saveParams(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.selectKeys[2]}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: this.activeName,
          attr_vals: row.attr_vals.join(' '),
        });
      if (res.meta.status !== 200) {
        return this.$message.error("添加失败");
      }
      this.$message.success("添加成功");
      
    },
    // tag标签移除事件
    removeTag(i,row){
      // 截取数组
      row.attr_vals.splice(i,1)
      // 调用方法
      this.saveParams(row)
    }
  },

  computed: {
    isDisable() {
      return this.selectKeys.length == 3 ? false : true;
    },
    // 根据激活面板的不同 返回不同的字符
    Text() {
      return this.activeName == "many" ? "动态参数" : "静态属性";
    },
  },

  created() {
    this.getCateList();
  },
};
</script>

<style lang="less" scoped>
.el-cascader {
  width: 280px;
  margin-top: 20px;
  margin-bottom: 10px;
}
.input-new-tag {
  width: 200px;
}
</style>